package jp.co.hcs.attendancemanagement.inputdailyattendance.logic;

import java.sql.SQLException;
import java.util.Date;

import jp.co.hcs.attendancemanagement.AMConstants;
import jp.co.hcs.attendancemanagement.AMResourceKeyConstants;
import jp.co.hcs.attendancemanagement.AMResourceManager;
import jp.co.hcs.attendancemanagement.StrutsMessageConstants;
import jp.co.hcs.attendancemanagement.common.ApprovalRecordData;
import jp.co.hcs.attendancemanagement.common.ApprovalRecordRegister;
import jp.co.hcs.attendancemanagement.data.entity.RestTimeActual;
import jp.co.hcs.attendancemanagement.data.entity.SubstituteHolidayActual;
import jp.co.hcs.attendancemanagement.data.entity.WorkingTimeActual;
import jp.co.hcs.attendancemanagement.exception.AMSQLException;
import jp.co.hcs.attendancemanagement.inputdailyattendance.actionform.InputDailyAttendanceForm;
import jp.co.hcs.attendancemanagement.inputdailyattendance.logic.dto.DailyWorkingActualResultDTO;
import jp.co.hcs.attendancemanagement.util.StringUtil;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class DeleteDailyWorkingLogic extends InputDailyWorkingLogicBase {
    /**
     * Delete daily working.
     * 
     * @param form
     *            the form
     * @return the action messages
     * @throws SQLException
     *             the sQL exception
     * @throws AMSQLException
     */
    public ActionMessages deleteDailyWorking(InputDailyAttendanceForm form)
            throws AMSQLException {
        // [xu ly client] confirm popup to delete

        ActionMessages errors = new ActionMessages();

        String employeeId = form.getUserId();
        String currentYear = form.getYear();
        String currentMonth = form.getMonth();
        String currentDay = form.getDay();
        String yearMonth = currentYear + currentMonth;

        try {
            daoFactory.startTransaction();

            DailyWorkingActualResultDTO dailyWorking = form.getTimeDTO();

            // --get job division
            String jobType = dailyWorking.getJobDivision();

            // delete daily data
            // --get Substitute leave adding No. and Take leave No.
            String substituteLeaveAddingNo = dailyWorking
                    .getAddedSubstituteHolidayNo();
            String takeLeaveNo = dailyWorking.getTakingVacationNo();
            if (StringUtil.isEmpty(substituteLeaveAddingNo)
                    || StringUtil.isEmpty(takeLeaveNo)) {
                WorkingTimeActual workingTimeActual = getWorkingTimeActualDAO()
                        .selectWorkingTimeActualByPrimaryKey(employeeId,
                                currentDay, yearMonth);
                if (workingTimeActual != null) {
                    substituteLeaveAddingNo = workingTimeActual
                            .getAdditionalHolidayNo();
                    takeLeaveNo = workingTimeActual.getTakingVacationNo();
                } else {
                    // jump to 25.2.9
                }
            }

            // --get Substitute leave time
            String substituteLeaveTakingNo = "";
            if (!StringUtil.isEmpty(takeLeaveNo)
                    && AMConstants.SUBSTITUTE_LEAVE.equals(jobType)) {
                RestTimeActual rtaObj = getRestTimeActualDAO()
                        .selectRestTimeActualByPrimaryKey(takeLeaveNo);
                if (rtaObj != null) {
                    substituteLeaveTakingNo = rtaObj.getChangeHolidayAddingNo();
                } else {
                    errors.add(
                            ActionErrors.GLOBAL_MESSAGE,
                            new ActionMessage(
                                    StrutsMessageConstants.ALARM_W1061_ERROR,
                                    AMResourceManager
                                            .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                    return errors;
                }
            }

            // --initialize substitute leave delete time
            if (!StringUtil.isEmpty(substituteLeaveTakingNo)) {
                int result = getSubstituteHolidayActualDAO().deleteSubstituteLeaveTakingDayById(substituteLeaveTakingNo);
                if (result == 0) {
                    // rollback 25.1
                    errors.add(
                            ActionErrors.GLOBAL_MESSAGE,
                            new ActionMessage(
                                    StrutsMessageConstants.ALARM_W1061_ERROR,
                                    AMResourceManager
                                            .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                    return errors;
                }
            }

            // --delete data take leave
            if (!StringUtil.isEmpty(takeLeaveNo)) {
                try {
                    getRestTimeActualDAO().deleteRestTimeActualByPrimaryKey(
                            takeLeaveNo);
                } catch (SQLException e) {
                    errors.add(
                            ActionErrors.GLOBAL_MESSAGE,
                            new ActionMessage(
                                    StrutsMessageConstants.ALARM_W1061_ERROR,
                                    AMResourceManager
                                            .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                    return errors;
                }
            }

            // --check su dung het data Substitute leave
            Date substituteLeaveDeleteDay = null;
            if (!StringUtil.isEmpty(substituteLeaveAddingNo)) {
                SubstituteHolidayActual shaObj = getSubstituteHolidayActualDAO()
                        .selectSubstituteHolidayActualByPrimaryKey(
                                substituteLeaveAddingNo);
                if (shaObj != null) {
                    substituteLeaveDeleteDay = shaObj
                            .getSubstituteHolidayDeleteDay();
                    if (substituteLeaveDeleteDay != null) {
                        errors.add(
                                ActionErrors.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        StrutsMessageConstants.ALARM_W1063_ERROR,
                                        AMResourceManager
                                                .getMessage(AMResourceKeyConstants.FIELD_SUBSTITUTELEAVETAKINGDAY)));
                        return errors;
                    }
                } else {
                    // rollback 25.1
                    errors.add(
                            ActionErrors.GLOBAL_MESSAGE,
                            new ActionMessage(
                                    StrutsMessageConstants.ALARM_W1061_ERROR,
                                    AMResourceManager
                                            .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                    return errors;
                }
            }

            // --delete data Substitute leave result
            if (!StringUtil.isEmpty(substituteLeaveAddingNo)) {
                try {
                    getSubstituteHolidayActualDAO()
                            .deleteSubstituteHolidayActualByPrimaryKey(
                                    substituteLeaveAddingNo);
                } catch (SQLException e) {
                    errors.add(
                            ActionErrors.GLOBAL_MESSAGE,
                            new ActionMessage(
                                    StrutsMessageConstants.ALARM_W1061_ERROR,
                                    AMResourceManager
                                            .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                    return errors;
                }
            }

            // --25.2.7 delete data Daily working result
            try {
                getWorkingTimeActualDAO().deleteWorkingTimeActualByPrimaryKey(
                        employeeId, currentDay, yearMonth);
            } catch (SQLException e) {
                errors.add(
                        ActionErrors.GLOBAL_MESSAGE,
                        new ActionMessage(
                                StrutsMessageConstants.ALARM_W1061_ERROR,
                                AMResourceManager
                                        .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                return errors;
            }

            // --25.2.8 delete data Rest time
            try {
                getRestTimeDAO().deleteRestTimeInDay(employeeId, currentDay,
                        yearMonth);
            } catch (SQLException e) {
                errors.add(
                        ActionErrors.GLOBAL_MESSAGE,
                        new ActionMessage(
                                StrutsMessageConstants.ALARM_W1061_ERROR,
                                AMResourceManager
                                        .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                return errors;
            }

            // --25.2.9 delete data Daily effort result
            try {
                getEffortActualDAO().deleteEffortActualInDay(employeeId,
                        currentDay, yearMonth);
            } catch (SQLException e) {
                errors.add(
                        ActionErrors.GLOBAL_MESSAGE,
                        new ActionMessage(
                                StrutsMessageConstants.ALARM_W1061_ERROR,
                                AMResourceManager
                                        .getMessage(AMResourceKeyConstants.ACTION_DELETEPROCESS)));
                return errors;
            }

            // --Update data daily working approval
            ApprovalRecordData approvalData = new ApprovalRecordData();
            approvalData.setEmployeeId(employeeId);
            approvalData.setApprovalTypeId(AMConstants.APPROVAL_TYPE_DAILY);
            approvalData.setTargetYearMonth(yearMonth);
            approvalData.setTargetDay(currentDay);
            approvalData.setTimingRegistCode(0);
            approvalData.setDayRegistCode(2);
            approvalData.setEffortRegistCode(2);
            approvalData.setApplicationNo("");
            approvalData.setProgramId(AMConstants.PGM_5031_SCREEN_ID);
            ApprovalRecordRegister approvalRegister = new ApprovalRecordRegister();
            int resultCode = approvalRegister.registerApproval(approvalData);
            if (resultCode == AMConstants.ERROR_FINISH) {
                // rollback
                errors.add(
                        ActionErrors.GLOBAL_MESSAGE,
                        new ActionMessage(
                                StrutsMessageConstants.ALARM_W1061_ERROR,
                                AMResourceManager
                                        .getMessage(AMResourceKeyConstants.ACTION_UPDATEPROCESS)));
                return errors;
            }

            // commit data
            daoFactory.commitTransaction();

        } catch (SQLException e) {
            throw new AMSQLException(e.getMessage());
        } finally {
            try {
                daoFactory.endTransaction();
            } catch (SQLException e) {
                throw new AMSQLException(e.getMessage());
            }
        }

        // show successful message

        return errors;
    }
}
